package com.zwy.Shopping.servlet_;

import com.zwy.Shopping.dao.ProductDao;
import com.zwy.Shopping.dao.impl.ProductDaoImpl;
import com.zwy.Shopping.model.Product;

import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import static java.lang.System.out;

@WebServlet("/modify_product")
@MultipartConfig
public class ModifyProductServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("productName");
        String marketPriceStr = request.getParameter("productMarketPrice");
        String priceStr = request.getParameter("productPrice");
        String stockStr = request.getParameter("productStock");
        int id = (Integer) request.getSession().getAttribute("modify_productId");

        //上传到本地资源
        //并没有上传到out
        Part part = request.getPart("productImage");
        String imageName = part.getSubmittedFileName();
        String path2 = "D:\\学习\\服装购买系统\\ShoppingClothes\\out\\artifacts\\ShoppingClothes_Web_exploded\\img\\";
        String webPath = path2 + imageName;
        File fileOnWeb = new File(webPath);
        if(fileOnWeb.exists()) {
            fileOnWeb.delete();
        }
            part.write(webPath);


        String localPath = "D:\\学习\\服装购买系统\\ShoppingClothes\\web\\img\\" + imageName;
        File fileOnLocal = new File(localPath);
        if(fileOnLocal.exists()) {
            fileOnLocal.delete();}
            Files.copy(fileOnWeb.toPath(), fileOnLocal.toPath(), StandardCopyOption.REPLACE_EXISTING); // 使用Java NIO复制文件


        Product product = new Product();
        product.setName(name);
        product.setImage(imageName);
        product.setPrice(new BigDecimal(priceStr));
        product.setMarketPrice(new BigDecimal(marketPriceStr));
        product.setId(id);
        product.setStock(Integer.parseInt(stockStr));
        ProductDao productDao = new ProductDaoImpl();
        boolean success = productDao.modifyProduct(product);
        if (success) {
            out.println("修改成功");
            request.setAttribute("message", "修改成功");
            request.setAttribute("page", "admin_index.jsp");
            request.getRequestDispatcher("alert.jsp").forward(request, response);
        } else {
            out.println("修改失败");
            request.setAttribute("message", "修改失败");
            request.setAttribute("page", "admin_index.jsp");
            request.getRequestDispatcher("alert.jsp").forward(request, response);
        }
    }
}
